package com.gujiangbo.thread;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 防止重复执行
 */
public class PreventDuplicated {

    private final static String LOCK_PATH = "/Users/gujiangbo/Desktop/";
    private final static String LOCK_FILE = ".lock";
    private final static String PERMISSIONS = "rw-------";

    public static void main(String[] args) throws IOException {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println(" the program received kill SIGNAL");
            getLockFile().toFile().delete();
        }));

        checkRunning();

        for (int i = 0; i < 30; i++) {
            try {
                TimeUnit.SECONDS.sleep(1);
                System.out.println("the program is running ....");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 检查运行状态，如果运行抛异常，没有运行 则创建锁文件对象
     *
     * @throws IOException
     */
    private static void checkRunning() throws IOException {
        Path path = getLockFile();
        if (path.toFile().exists()) {
            throw new RuntimeException("the program already running");
        }
        Set<PosixFilePermission> posixFilePermissions = PosixFilePermissions.fromString(PERMISSIONS);
        Files.createFile(path, PosixFilePermissions.asFileAttribute(posixFilePermissions));
    }

    /**
     * 获取锁对象文件
     *
     * @return
     */
    private static Path getLockFile() {
        return Paths.get(LOCK_PATH, LOCK_FILE);
    }

}
